package com.jason.jasonapp.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

import com.jason.jasonapp.R;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.widget.Toast;

public class JasonCurrentBostonDownloader extends Thread {

	private Activity parentActivity;
	private boolean download;
	
	public JasonCurrentBostonDownloader(Activity activity) {
		parentActivity = activity;
		download = false;
	}
	
	@Override
	public void run() {
		testfunc();
	}
	
	private void testfunc() {
		String lCurrent = null;
		try {
			lCurrent = getLocalCurrent();
		} catch(FileNotFoundException e) {
		} catch(IOException e) {
			return;
		}
		
		if(isWifiConnected()) {
			try {
				String sCurrent = getServerCurrent();
				if(lCurrent != null) {
					if(sCurrent.equals(lCurrent)) {
						printToast("Download not needed");
						return;
					}
				}
				//download file;
				URL serverBostonURL = getServerBostonFileURL(sCurrent + ".mp3");
				String localFileName = getLocalBostonFileName(sCurrent + ".mp3");
				printToast("Starting download " + serverBostonURL.toString());
				downloadRemoteFile(serverBostonURL, localFileName);
				setLocalCurrent(sCurrent);
				printToast("Done downloading");
			} catch(Exception e) {
				printToast(e.toString());
				return;
			}
		}
	}
	
	private URL getServerBostonFileURL(String sCurrentMP3) throws MalformedURLException {
		return new URL(parentActivity.getResources().getString(R.string.const_urlBostonDirectory) + sCurrentMP3);
	}
	
	private void downloadRemoteFile(URL url, String localFileName) throws IOException{
		InputStream is = url.openStream();
		FileOutputStream fos = new FileOutputStream(localFileName);
		
		byte[] buffer = new byte[4096];
		int len = 0;
		while((len = is.read(buffer)) > 0) {
			fos.write(buffer, 0, len);
		}
		fos.close();
		is.close();
	}
	
	private void setLocalCurrent(String current) throws IOException {
		String fileName = getLocalCurrentFileName();
		File oldFile = new File(fileName);
		oldFile.delete();
		FileWriter currentFile = new FileWriter(fileName);
		currentFile.write(current);
		currentFile.close();
	}
	
	private boolean isWifiConnected() {
		ConnectivityManager manager = (ConnectivityManager)parentActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		return ni.isConnected();
	}
	
	private String getServerCurrent() throws FileNotFoundException, IOException {
		String current = null;
		URL currentFile = getBostonURL();
		BufferedReader bufReader = new BufferedReader(new InputStreamReader(currentFile.openStream()));
		current = bufReader.readLine();
		bufReader.close();
		return current;
	}
	
	private final URL getBostonURL() throws MalformedURLException {
		return new URL(parentActivity.getResources().getString(R.string.const_urlBostonCurrent));
	}
	
	private String getLocalCurrent() throws FileNotFoundException, IOException {
		String path = getLocalCurrentFileName();
		BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
		String current = bufReader.readLine();
		bufReader.close();
		return current;
	}
	
	private String getLocalCurrentFileName() throws IOException {
		return prepareDirectory(parentActivity.getResources().getString(R.string.const_appName)).getPath() + "/current";
	}
	
	private String getLocalBostonFileName(String current) throws IOException {
		return prepareDirectory(parentActivity.getResources().getString(R.string.const_appName)).getPath() + "/" + current;
	}
	
	private File prepareDirectory(String appName) throws IOException {
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			File path = new File(Environment.getExternalStorageDirectory().getPath() + "/" + appName);
			if(!path.exists()) {
				path.mkdirs();
			}
			if(path.exists() && path.isDirectory()) {
				return path;
			}
		}
		throw new IOException();
	}
	
	private void printToast(final String str) {
		parentActivity.runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(parentActivity, str, Toast.LENGTH_LONG).show();
				}
			});
	}
}
